import { Body, Controller, Get, Param, Post, Query } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { MenuService } from "./menu.service";
import { DataObj } from "src/common/class/data-obj.class";
import { ReqAddMenuDto, ReqSearchDto, ReqUpdateMenu } from "./dto/req-menu.dto";
import { ApiException } from "src/common/exceptions/api.exception";

@ApiTags("菜单管理")
@Controller("system/menu")
export class MenuController {
  constructor(private readonly menuService: MenuService) {}

  // 新增菜单
  @Post("addMenu")
  async addMenu(@Body() reqAddMenuDto: ReqAddMenuDto) {
    await this.menuService.addOrUpdate(reqAddMenuDto);
  }

  // 修改菜单
  @Post("editMenu")
  async edit(@Body() reqUpdateMenu: ReqUpdateMenu) {
    await this.menuService.addOrUpdate(reqUpdateMenu);
  }

  @Get("list")
  async list(@Query() reqSearchDto: ReqSearchDto) {
    const menuArr = await this.menuService.list(reqSearchDto);
    return DataObj.create(menuArr);
  }

  /**
   * @description: 获取菜单树
   * @return {*}
   */
  @Get("menuTree")
  async getMenuTree() {
    const menuTree = await this.menuService.getMenuTree();
    return DataObj.create(menuTree);
  }

  @Post("deleteMenu")
  async deleteMenu(@Body("menu_id") menu_id: string) {
    const childs = await this.menuService.findChildrenByParentId(menu_id);
    if (childs && childs.length) throw new ApiException("该菜单下还存在其他菜单，无法删除！");
    await this.menuService.delete(menu_id);
  }
}
